//获取应用实例
var app = getApp()
Page({
  data: {
    
  },
  onLoad: function (e) {
    var that = this;
    if (e && e.enterfrom) {
      var enterfrom = e.enterfrom == 'share' ? true : false;
      that.setData({
        enterfrom: enterfrom
      })
    }
    if (e && e.title) {
      app.setNavtitle(e.title);
      that.setData({
        title: e.title
      })
    } else {
      app.setNavtitle('趣味答题');
    }
  },
  onShow:function(){
    var that = this;
    if (!app.globalData.plumSession) {
      console.log("暂未获取到session");
      app.wechatSq(that);
    } else {
      app.requestAd(that);
      that.requestIndexinfo();
    }
  },
  // 获取分享信息
  requestShareinfo: function () {
    var that = this;
    var mid = that.data.mid;
    var curtime = that.data.curtime;
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_subject_share_fetch_card',
        mid: mid,
        curtime: curtime
      },
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
        } else {
          console.log(res.data)
        }
      },
      complete: function () {

      }
    });
  },
  requestIndexinfo: function () {
    var that = this;
    var id = that.data.id;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_subject_redpacket_cfg'
      },
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
          that.setData({
            indexInfo: res.data.data,
            reviveCard: res.data.data.totalCard,
            startTime: res.data.data.openTime,
            endTime: res.data.data.endTime,
            rules: res.data.data.rule
          })
          var questionShare = {
            shareTitle: res.data.data.shareTitle,
            shareCover: res.data.data.shareCover
          }
          app.globalData.questionShare = questionShare;
          app.globalData.awardMobile = res.data.data.phone;
          app.globalData.answerTime = res.data.data.answerTime;
          // clearInterval(that.data.intervarID);
          // that.countDjs();
        } else {
          console.log(res.data)
          app.errorTip(that, res.data.em, 2000);
          that.setData({
            indexInfo:''
          })
        }
      },
      complete: function () {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    });
  },
  countDjs: function () {
    var that = this;
    var startTime = that.data.startTime;
    var endTime = that.data.endTime;
    var curtime = parseInt((new Date()).getTime()/1000); //避免页面渲染倒计时的时候出现一秒的延迟。
    console.log(curtime);
    var startSpan1 = startTime - curtime;
    var endSpan2 = endTime - curtime;
    console.log(startSpan1);
    console.log(endSpan2);
    if (startSpan1 > 0) {
      that.setData({
        startDsec: '开始',
        gameOver:false
      })
      that.djs(startSpan1, 'start');
    } else {
      if (endSpan2>0){
        that.setData({
          startDsec: '结束',
          gameOver: false
        })
        that.djs(endSpan2);
      }else{
        that.setData({
          gameOver: true
        })
      }
    }
    that.data.intervarID = setInterval(function () {
      var nowTime = parseInt((new Date()).getTime() / 1000);
      var startSpan = startTime - nowTime;
      var endSpan = endTime - nowTime;
      if (startSpan > 0) {
        that.setData({
          startDsec: '开始',
          isAnswering: false,
          gameOver: false
        })
        that.djs(startSpan, 'start');
      } else {
        if (endSpan2 > 0) {
          that.setData({
            startDsec: '结束',
            isAnswering: true,
            gameOver: false
          })
          that.djs(endSpan);
        } else {
          that.setData({
            gameOver: true,
            isAnswering:false
          })
        }
      }
    }, 1000)
  },
  djs: function (time,type) {
    var that = this;
    var leftTime = time;
    that.setData({
      leftTime: leftTime
    })
    // console.log(leftTime);
    if (leftTime > 0) {
      var days = parseInt(leftTime / 60 / 60 / 24, 10); //计算剩余的天数 
      var hours = parseInt(leftTime / 60 / 60 % 24, 10); //计算剩余的小时 
      var minutes = parseInt(leftTime / 60 % 60, 10);//计算剩余的分钟 
      var seconds = parseInt(leftTime % 60, 10);//计算剩余的秒数 
      days = days < 10 ? '0' + days : days;
      hours = hours < 10 ? '0' + hours : hours;
      minutes = minutes < 10 ? '0' + minutes : minutes;
      seconds = seconds < 10 ? '0' + seconds : seconds;
      that.setData({
        days: days,
        hours: hours,
        minutes: minutes,
        seconds: seconds
      })
      if (days == '00' && hours == '00' && minutes == '00' && seconds == '00') {
        clearInterval(that.data.intervarID);
        if (type) {
          that.countDjs();
        }else{
          that.setData({
            gameOver:true,
            isAnswering: false
          })
        }
      }
    } else {
      clearInterval(that.data.intervarID);
      that.setData({
        hours: '00',
        minutes: '00',
        seconds: '00',
      })
      if (type){
        that.countDjs();
      }else{
        that.setData({
          gameOver: true,
          isAnswering: false
        })
      }
    }
  },
  onPullDownRefresh: function () {
    var that = this;
    that.setData({
      page: 0,
      noMoretip: false,
      showLoading: true,
    })
    that.onShow();
    that.onLoad();
  },
  answerQuestion: function (e) {
    var type = e.currentTarget.dataset.type;
    var times = e.currentTarget.dataset.times;
    if (times && times>0){
      wx.navigateTo({
        url: '/subpages/answerQuestion/answerQuestion?from=sub&&type='+type
      })
    } else {
      app.errorTip(this, "答题次数已用完！", 2000);
    }
  },
  redbagWithdraw: function () {
    wx.navigateTo({
      url: '/pages/incomeWithdraw/incomeWithdraw'
    })
  },
  //列表数据
  requestRedbackList: function () {
    var that = this;
    var data = {};
    var page = that.data.page;
    data.map = 'applet_subject_redpacket_list';
    data.page = page;
    data.status = that.data.couponStatus;
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          var allArr = [];
          var initArr = that.data.redbackList;
          var curArr = res.data.data;
          var lastPageLength = curArr.length;
          if (page > 0) {
            allArr = initArr.concat(curArr);
          } else {
            allArr = res.data.data;
          }
          that.setData({
            redbackList: allArr
          })
          if (lastPageLength < 10) {
            that.setData({
              noMoretip: true,
              showLoading: false
            });
          }
          console.log(that.data.redbackList);
        } else {
          if (page <= 0) {
            that.setData({
              redbackList: [],
              noMoretip: false,
              showLoading: false
            })
          } else {
            that.setData({
              noMoretip: true,
              showLoading: false
            });
          }
        }
      },
      complete: function () {
        wx.stopPullDownRefresh();
      }
    });
  },
  scrolltoupper: function () {
    this.setData({
      page: 0,
      noMoretip: false,
      showLoading: true
    });
    this.requestRedbackList();
    console.log("下拉刷新");
  },
  scrolltolower: function () {
    var that = this;
    console.log("到达页面底部")
    var isMore = that.data.noMoretip;
    var page = that.data.page;
    page++;
    that.setData({
      page: page
    });
    if (isMore) {
      console.log("已完成或正在加载");
    } else {
      that.requestRedbackList();
    }
  },
  toQuestionrules: function () {
    var that = this;
    wx.setStorage({
      key: 'questionRule',
      data: that.data.rules,
      success: function () {
        wx.navigateTo({
          url: '/subpages/questionRules/questionRules',
        })
      }
    })
  },
  toAnswerRank:function(){
    wx.navigateTo({
      url: '/subpages/answerRank/answerRank'
    })
  },
  tomyAward: function () {
    wx.navigateTo({
      url: '/subpages/myAward/myAward'
    })
  },
  toscoreChange: function () {
    var that = this;
    var totalPoints = that.data.indexInfo.totalPoints;
    var pointsCost = that.data.indexInfo.pointsCost;
    wx.navigateTo({
      url: '/subpages/scoreChange/scoreChange?totalPoints=' + totalPoints + '&pointsCost=' + pointsCost
    })
  },
  backsy: function () {
    app.backHome();
  },
  onShareAppMessage: function () {
    var that = this;
    var questionShare = app.globalData.questionShare ? app.globalData.questionShare : '';
    var title = questionShare.shareTitle ? questionShare.shareTitle : '趣味答题';
    var cover = questionShare.shareCover ? questionShare.shareCover : 'http://tiandiantong.oss-cn-beijing.aliyuncs.com/images/share-poster.jpg';
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_subject_fetch_use_card',
        type: 'fetch'
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          app.errorTip(that, res.data.data.msg, 2000);
          console.log(res.data.data.msg);
          that.setData({
            reviveCard: res.data.data.num
          })
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {

      }
    });
    return {
      title: title,
      imageUrl: cover,
      path: '/subpages/questionIndex/questionIndex?enterfrom=share'
    }
  },
})

